import React, { useState, useEffect } from 'react';
import { 
  Card, 
  List, 
  Button, 
  Space, 
  Tag, 
  Input, 
  Select, 
  Row, 
  Col,
  Upload,
  message,
  Spin,
  Modal,
  Image,
  Typography
} from 'antd';
import { 
  UploadOutlined, 
  FilePdfOutlined, 
  FileWordOutlined, 
  FileExcelOutlined, 
  FileOutlined,
  SearchOutlined,
  FileImageOutlined,
  VideoCameraOutlined,
  FileTextOutlined,
  EyeOutlined,
  DownloadOutlined,
  PlayCircleOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons';
import api from '../services/api';

const { Search } = Input;
const { Option } = Select;
const { Paragraph } = Typography;

const ResourceCenterPage = () => {
  const [resources, setResources] = useState([]);
  const [loading, setLoading] = useState(false);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewFile, setPreviewFile] = useState(null);
  const [filters, setFilters] = useState({
    type: null,
    category: null
  });

  // 获取资源列表
  const fetchResources = async () => {
    setLoading(true);
    try {
      const params = {};
      if (filters.type) params.type = filters.type;
      if (filters.category) params.category = filters.category;
      
      let apiResources = [];
      try {
        const response = await api.get('/resources', { params });
        apiResources = response.data || [];
      } catch (apiError) {
        console.log('后端API不可用，使用本地数据:', apiError);
        apiResources = [];
      }
      
      // 获取localStorage中保存的资源
      const localResources = JSON.parse(localStorage.getItem('uploadedResources') || '[]');
      
      // 合并API资源和本地资源
      const allResources = [...localResources, ...apiResources];
      
      // 根据过滤条件过滤资源
      let filteredResources = allResources;
      if (filters.type) {
        filteredResources = filteredResources.filter(resource => resource.type === filters.type);
      }
      if (filters.category) {
        filteredResources = filteredResources.filter(resource => resource.category === filters.category);
      }
      
      setResources(filteredResources);
    } catch (error) {
      console.error('获取资源列表失败:', error);
      message.error('获取资源列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchResources();
  }, [filters]);

  const getFileIcon = (name, type) => {
    const extension = name ? name.split('.').pop().toLowerCase() : '';
    
    // 根据文件扩展名判断类型
    if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(extension)) {
      return <FileImageOutlined style={{ fontSize: '24px', color: '#52c41a' }} />;
    }
    if (['mp4', 'avi', 'mkv', 'mov', 'wmv', 'flv'].includes(extension)) {
      return <VideoCameraOutlined style={{ fontSize: '24px', color: '#722ed1' }} />;
    }
    if (['pdf'].includes(extension)) {
      return <FilePdfOutlined style={{ fontSize: '24px', color: '#ff4d4f' }} />;
    }
    if (['doc', 'docx'].includes(extension)) {
      return <FileWordOutlined style={{ fontSize: '24px', color: '#1890ff' }} />;
    }
    if (['xls', 'xlsx'].includes(extension)) {
      return <FileExcelOutlined style={{ fontSize: '24px', color: '#52c41a' }} />;
    }
    if (['txt', 'md'].includes(extension)) {
      return <FileTextOutlined style={{ fontSize: '24px', color: '#8c8c8c' }} />;
    }
    
    // 根据类型判断
    switch (type) {
      case 'manual':
        return <FilePdfOutlined style={{ fontSize: '24px', color: '#ff4d4f' }} />;
      case 'firmware':
        return <FileOutlined style={{ fontSize: '24px', color: '#1890ff' }} />;
      case 'driver':
        return <FileOutlined style={{ fontSize: '24px', color: '#52c41a' }} />;
      case 'video':
        return <VideoCameraOutlined style={{ fontSize: '24px', color: '#722ed1' }} />;
      default:
        return <FileOutlined style={{ fontSize: '24px', color: '#8c8c8c' }} />;
    }
  };

  // 文件类型检测
  const getFileType = (name) => {
    if (!name) return 'unknown';
    const extension = name.split('.').pop().toLowerCase();
    
    if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(extension)) {
      return 'image';
    }
    if (['mp4', 'avi', 'mkv', 'mov', 'wmv', 'flv'].includes(extension)) {
      return 'video';
    }
    if (['pdf'].includes(extension)) {
      return 'pdf';
    }
    if (['txt', 'md', 'log'].includes(extension)) {
      return 'text';
    }
    if (['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'].includes(extension)) {
      return 'office';
    }
    return 'unknown';
  };

  // 文件预览函数
  const handlePreview = (file) => {
    const fileType = getFileType(file.name);
    
    if (fileType === 'image' || fileType === 'video' || fileType === 'pdf' || fileType === 'text') {
      setPreviewFile({ ...file, fileType });
      setPreviewVisible(true);
    } else {
      message.info('该文件类型暂不支持预览，请下载后查看');
    }
  };

  // 文件下载函数
  const handleDownload = (file) => {
    if (file.path) {
      const link = document.createElement('a');
      link.href = file.path;
      link.download = file.name;
      link.target = '_blank';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } else {
      message.error('文件路径不存在');
    }
  };

  // 删除资源函数
  const handleDelete = (resource) => {
    Modal.confirm({
      title: '确认删除',
      icon: <ExclamationCircleOutlined />,
      content: `确定要删除资源 "${resource.name}" 吗？此操作不可恢复。`,
      okText: '确认删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          // 如果资源有ID，说明是从后端API获取的，尝试调用删除API
          if (resource.id && typeof resource.id === 'number' && resource.id < Date.now() - 1000000000000) {
            try {
              await api.delete(`/resources/${resource.id}`);
              message.success('资源删除成功');
            } catch (apiError) {
              console.log('API删除失败，从本地删除:', apiError);
              // API删除失败，从localStorage删除
              const localResources = JSON.parse(localStorage.getItem('uploadedResources') || '[]');
              const updatedResources = localResources.filter(r => r.id !== resource.id);
              localStorage.setItem('uploadedResources', JSON.stringify(updatedResources));
              message.success('资源删除成功（本地删除）');
            }
          } else {
            // 本地资源，从localStorage删除
            const localResources = JSON.parse(localStorage.getItem('uploadedResources') || '[]');
            const updatedResources = localResources.filter(r => r.id !== resource.id);
            localStorage.setItem('uploadedResources', JSON.stringify(updatedResources));
            message.success('资源删除成功');
          }
          
          // 重新获取资源列表
          await fetchResources();
        } catch (error) {
          console.error('删除资源失败:', error);
          message.error('删除资源失败');
        }
      },
    });
  };

  // 渲染预览内容
  const renderPreviewContent = () => {
    if (!previewFile) return null;
    
    switch (previewFile.fileType) {
      case 'image':
        return (
          <Image
            width="100%"
            src={previewFile.path}
            alt={previewFile.name}
          />
        );
      case 'video':
        return (
          <video 
            width="100%" 
            controls 
            style={{ maxHeight: '400px' }}
          >
            <source src={previewFile.path} type="video/mp4" />
            您的浏览器不支持视频播放。
          </video>
        );
      case 'pdf':
        return (
          <iframe 
            src={previewFile.path} 
            width="100%" 
            height="500px"
            style={{ border: 'none' }}
            title={previewFile.name}
          >
            您的浏览器不支持PDF预览。
          </iframe>
        );
      case 'text':
        return (
          <div style={{ 
            padding: '16px', 
            backgroundColor: '#f5f5f5', 
            borderRadius: '4px',
            maxHeight: '400px',
            overflow: 'auto'
          }}>
            <Paragraph>
              文本文件预览功能开发中...
            </Paragraph>
          </div>
        );
      default:
        return <div>暂不支持该文件类型的预览</div>;
    }
  };

  const handleUpload = async (file) => {
    setLoading(true);
    try {
      // 创建 FormData 对象上传文件
      const formData = new FormData();
      formData.append('file', file);
      formData.append('name', file.name);
      formData.append('type', 'manual'); // 默认类型
      formData.append('description', `上传的资源文件: ${file.name}`);
      
      try {
        // 尝试调用后端API上传
        const response = await api.post('/resources/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        });
        
        // 重新获取资源列表
        await fetchResources();
        message.success(`${file.name} 上传成功`);
        
      } catch (apiError) {
        console.log('API上传失败，使用模拟数据:', apiError);
        
        // 如果后端API不可用，使用模拟数据并保存到localStorage
        const newResource = {
          id: Date.now(),
          name: file.name,
          type: 'manual',
          version: 'v1.0',
          description: `上传的资源文件: ${file.name}`,
          path: URL.createObjectURL(file),
          created_at: new Date().toISOString()
        };
        
        // 保存到localStorage以保持数据
        const existingResources = JSON.parse(localStorage.getItem('uploadedResources') || '[]');
        const updatedResources = [newResource, ...existingResources];
        localStorage.setItem('uploadedResources', JSON.stringify(updatedResources));
        
        // 更新组件状态
        setResources(updatedResources);
        message.success(`${file.name} 上传成功（本地存储）`);
      }
    } catch (error) {
      console.error('上传失败:', error);
      message.error(`${file.name} 上传失败`);
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = (value) => {
    // 搜索功能可以在这里实现
    console.log('搜索:', value);
  };

  const handleTypeChange = (value) => {
    setFilters({ ...filters, type: value });
  };

  const handleCategoryChange = (value) => {
    setFilters({ ...filters, category: value });
  };

  return (
    <div>
      <h2>资源中心</h2>
      
      <Card style={{ marginBottom: 16 }}>
        <Row gutter={16}>
          <Col span={8}>
            <Search 
              placeholder="搜索资源" 
              allowClear 
              onSearch={handleSearch}
              enterButton={<SearchOutlined />}
            />
          </Col>
          <Col span={6}>
            <Select 
              placeholder="资源类型" 
              style={{ width: '100%' }} 
              allowClear
              onChange={handleTypeChange}
            >
              <Option value="manual">手册</Option>
              <Option value="firmware">固件</Option>
              <Option value="driver">驱动</Option>
              <Option value="video">视频</Option>
            </Select>
          </Col>
          <Col span={6}>
            <Select 
              placeholder="分类" 
              style={{ width: '100%' }} 
              allowClear
              onChange={handleCategoryChange}
            >
              <Option value="hardware">硬件</Option>
              <Option value="software">软件</Option>
              <Option value="network">网络</Option>
            </Select>
          </Col>
          <Col span={4}>
            <Upload 
              beforeUpload={(file) => {
                handleUpload(file);
                return false; // 阻止自动上传
              }}
              showUploadList={false}
            >
              <Button icon={<UploadOutlined />} block>上传资源</Button>
            </Upload>
          </Col>
        </Row>
      </Card>
      
      {loading ? (
        <Spin size="large" style={{ display: 'block', margin: '50px auto' }} />
      ) : (
        <List
          grid={{ gutter: 16, column: 3 }}
          dataSource={resources}
          renderItem={item => {
            const fileType = getFileType(item.name);
            const canPreview = ['image', 'video', 'pdf', 'text'].includes(fileType);
            
            return (
              <List.Item>
                <Card 
                  hoverable
                  actions={[
                    canPreview ? (
                      <Button 
                        type="link" 
                        size="small" 
                        icon={<EyeOutlined />}
                        onClick={() => handlePreview(item)}
                      >
                        预览
                      </Button>
                    ) : (
                      <Button type="link" size="small" disabled>
                        预览
                      </Button>
                    ),
                    <Button 
                      type="link" 
                      size="small" 
                      icon={<DownloadOutlined />}
                      onClick={() => handleDownload(item)}
                    >
                      下载
                    </Button>,
                    <Button 
                      type="link" 
                      size="small" 
                      icon={<DeleteOutlined />}
                      onClick={() => handleDelete(item)}
                      danger
                    >
                      删除
                    </Button>
                  ]}
                >
                  <Space direction="vertical" style={{ width: '100%', textAlign: 'center' }}>
                    {getFileIcon(item.name, item.type)}
                    <h3 style={{ fontSize: '14px', margin: '8px 0' }}>{item.name}</h3>
                    <Tag color="blue">{item.type}</Tag>
                    {item.version && <Tag color="green">{item.version}</Tag>}
                    <Paragraph 
                      ellipsis={{ rows: 2 }} 
                      style={{ fontSize: '12px', margin: '8px 0' }}
                    >
                      {item.description}
                    </Paragraph>
                    <p style={{ fontSize: '12px', color: '#8c8c8c', margin: 0 }}>
                      上传时间: {new Date(item.created_at).toLocaleDateString()}
                    </p>
                  </Space>
                </Card>
              </List.Item>
            );
          }}
        />
      )}

      {/* 文件预览模态框 */}
      <Modal
        title={previewFile ? `预览: ${previewFile.name}` : '文件预览'}
        visible={previewVisible}
        onCancel={() => {
          setPreviewVisible(false);
          setPreviewFile(null);
        }}
        footer={[
          <Button key="download" icon={<DownloadOutlined />} onClick={() => handleDownload(previewFile)}>
            下载文件
          </Button>,
          <Button key="close" onClick={() => {
            setPreviewVisible(false);
            setPreviewFile(null);
          }}>
            关闭
          </Button>
        ]}
        width={800}
        centered
      >
        {renderPreviewContent()}
      </Modal>
    </div>
  );
};

export default ResourceCenterPage;